const express = require('express');
const router = express.Router();
const { Chapter , Course } = require('../../models');  
const { Op } = require('sequelize');  //模糊匹配查询
const { NotFoundError } = require('../../utils/errors');
const { success, failure } = require('../../utils/responses');
//列表查询 
router.get('/', async function(req, res, next) {
    try{
   
    //当前是第几页  
    const currentPage = Math.abs(Number(req.query.currentPage)) || 1;
    //每页显示多少条
    const pageSize = Math.abs(Number(req.query.pageSize))|| 10;
    //计算 offset
    const offset = (currentPage - 1) * pageSize; 
    const query = req.query
    if (!query.courseId) {
        throw new Error('获取章节列表失败，课程ID不能为空。');
      }
    const condition ={  //倒序
        ...getCondition(),
        order:[['id','ASC'], ['id', 'ASC']],
        limit: pageSize,
        offset
    } 

    condition.where = {
        courseId: {
          [Op.eq]: query.courseId
        }
      };
      
      if (query.title) {
        condition.where = {
          title: {
            [Op.like]: `%${ query.title }%`
          }
        };
      }
    // const chapters =await Chapter.findAll(condition)
    const {count ,rows} =await Chapter.findAndCountAll(condition)
    success(res,'success', {
        chapters: rows,
        pagination: {
            total: count,
            currentPage,
            pageSize
        } 
    },200)
    }catch(err){
        failure(res,err)
    }
});
//新增
router.post('/', async function(req, res, next) {
    try{
        const body = filterBody(req.body)
        const chapter = await Chapter.create(body)
        success(res,'success', chapter,201)
        }catch(err){
            failure(res,err)
        }
});
//id占位查询
router.get('/:id', async function(req, res, next) {
    try{
        const chapter = await getChapter(req)
        success(res,'success', chapter,201)
    }catch(err){
        failure(res,err)
    }
});
//删除章节
router.delete('/:id', async function(req, res, next) {
    try{
    const chapter = await getChapter(req)
    await chapter.destroy()
        success(res,'success', {
            status: true,
            msg: '删除成功',
        },201)
    }catch(err){
        failure(res,err)
    }
})
//修改章节
router.put('/:id', async function(req, res, next) {
    try{
        const body = filterBody(req.body)
        const chapter = await getChapter(req)
        await chapter.update(body)
        success(res,'success', {
            status: true,
            msg: '更新成功',
            data:{chapter}
        },200)
    }catch(err){
        failure(res,err)
    }
})


const bodyFilter = ['courseId','title','content','video','rank']
function filterBody(body) {
    const result = {}
    bodyFilter.forEach(key => {
        if(body[key]){
            result[key] = body[key]
        }
    })
    return result
}
async function getChapter(req) {
    const { id } = req.params;
    const condition = getCondition();
    const chapter = await Chapter.findByPk(id,condition)
    if( !chapter ) throw new NotFoundError(`ID:${id} 的章节不存在`)
    return chapter
}

/**
 * 公共方法：关联课程数据
 * @returns {{include: [{as: string, model, attributes: string[]}], attributes: {exclude: string[]}}}
 */
function getCondition() {
    return {
      attributes: { exclude: ['CourseId'] },
      include: [
        {
          model: Course,
          as: 'course',
          attributes: ['id', 'name']
        }
      ]
    }
  }
  
module.exports = router;
